﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Solution.Provide
{
    public static class DynamicViewModelHelper
    {
        /// <summary>
        /// 将对象[主要是匿名对象]转换为dynamic
        /// 
        /// 如果返回的是集合当然你也可以这么写：
        /// db.tab.ToList().Select(o =>
        //{
        //    dynamic rs = new ExpandoObject();
        //    rs.col = o.col;
        //    return rs;
        ///}
        /// 
        /// </summary>
        public static dynamic ToDynamic(this object value)
        {
            IDictionary<string, object> expando = new ExpandoObject();
            Type type = value.GetType();
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(type);
            foreach (PropertyDescriptor property in properties)
            {
                var val = property.GetValue(value);
                if (property.PropertyType.FullName.StartsWith("<>f__AnonymousType"))
                {
                    if (val != null)
                    {
                        dynamic dval = val.ToDynamic();
                        expando.Add(property.Name, dval);
                    }
                }
                else
                {
                    expando.Add(property.Name, val);
                }
            }
            return expando as ExpandoObject;
        }
    }
}
